﻿using System.Security.Claims;
using zhwy.saas.api.Services.Sinterface;

namespace zhwy.saas.api.Services
{
    public class CurrentUserService : ICurrentUserService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public CurrentUserService(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public int GetTenantId()
        {
            var tenantClaim = _httpContextAccessor.HttpContext?.User?
            .FindFirst("tenant_id")?.Value;

            return int.TryParse(tenantClaim, out var id) ? id : 0;
        }

        public long GetUserId()
        {
            var userIdClaim = _httpContextAccessor.HttpContext?.User?
                .FindFirst(ClaimTypes.NameIdentifier)?.Value;

            return long.TryParse(userIdClaim, out var id) ? id : 0;
        }

        public string GetUserName() =>
            _httpContextAccessor.HttpContext?.User?.Identity?.Name ?? "Anonymous";

        public bool IsAuthenticated() =>
            _httpContextAccessor.HttpContext?.User?.Identity?.IsAuthenticated ?? false;
    }
}
